<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2018\10\28 0028
 * Time: 10:03
 */
namespace app\admin\controller;
use app\admin\model\Databases;
use think\Db;
use think\Request;

class Field
{
    /**加载添加页面
     * @param Request $request
     * @return string|\think\response\View
     */
    public function show_add(Request $request){
        $pid = $request->param('pid',null);
        $model = $request->param('model',null);
        if(!$pid){
            return '请输入想哪个表加字段';
        }
        return view('add',['pid'=>$pid,'model'=>$model]);
    }

    /**添加字段
     * @param Request $request
     * @return int|string
     */
    public function add(Request $request){
        $data =$request->post();
        $bool = Databases::add_feild($data['model'],$data);
//        return '添加失败';
        if(!$bool){
            return '添加失败';
        }
        unset($data['model']);
        if(Db::name('table_field')->insert($data)){
            return 1;
        }else{
            return '添加失败';
        }
    }

    /**加载编辑字段
     * @param Request $request
     * @return string|\think\response\View
     */
    public function edit(Request $request){
        $id = $request->param('id',null);
        if(!$id){
            return '请输入修改的id';
        }
        $data = Db::name('table_field')->where('id',$id)->find();
        return view('edit',['data'=>$data]);
    }

    /**更新字段信息
     * @param Request $request
     * @return int|string
     */
    public function update(Request $request){
        $data = $request->post();
        $datas = Db::name('table_field')->where('id',$data['id'])->find();
        $model = (Db::name('model')->where('id',$datas['modelid'])->find())['surface'];
        if(!($datas['types']==$data['types'])||!($datas['lang']==$data['lang'])||!($data['field_title']==$datas['field_title'])){
            $bool = Databases::update_fieldattribute($model,$datas['field_title'],['name'=>$data['field_title'],'types'=>$data['types'],'lang'=>$data['lang']]);
            if(!$bool){
                return '修改失败';
            }
        }
        if(Db::name('table_field')->where('id',$data['id'])->update($data)){
            return 1;
        }else{
            return '你什么都没改变';
        }
    }

    /**删除字段
     * @param Request $request
     * @return int|string
     */
    public function del(Request $request){
        $id = $_POST['id'];
        //return $id;
        $data = Db::name('table_field')->where('id','in',$id)->select();
        foreach ($data as $value){
            $modelid = $value['modelid'];
            $table = (Db::name('model')->where('id',$modelid)->find())['surface'];
            $bool = Databases::dele_feild($table,$value['field_title']);
//            return $bool;
            if(!$bool){
                return '删除失败';
            }
        }
        if(Db::name('table_field')->where('id','in',$id)->delete()){
            return 1;
        }else{
            return '删除失败';
        }
    }
}